import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:sptapp/utils/string_tool.dart';
import '../../config/const.dart';
import '../../moudle/common_info.dart';
import '../../moudle/event_bus.dart';
import '../../moudle/message.dart';
import '../../utils/regex_tool.dart';
import '../../widget/common_widget.dart';

class MinSecurityChangeEmail extends StatefulWidget {
  final Map arguments;
  const MinSecurityChangeEmail({super.key, required this.arguments});

  @override
  State<MinSecurityChangeEmail> createState() => _MinSecurityChangeEmailState();
}

class _MinSecurityChangeEmailState extends State<MinSecurityChangeEmail> {

  TextEditingController accountController = TextEditingController();
  String? account;
  late int type;
  late StreamSubscription _subscription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    type = widget.arguments['type'] ?? 1; //1:修改邮箱 2:绑定邮箱
    _getEmail();
    _subscription = eventBus.on<UserInfoChange>().listen((val){
      if(mounted){setState(() {
        accountController.text = baseUserInfo['email']??'';
        account = accountController.text;
      });}
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _subscription.cancel();
  }

  _getEmail(){
    if(type == 2){
      return;
    }
    accountController.text = baseUserInfo['email']??'';
    account = accountController.text;
    if(mounted){
      setState(() {});
    }
  }

  _register()async{
    if(account == null || account!.isEmpty){
      return;
    }
    if(type == 1){
      Navigator.of(context).pushNamed('MinSecurityChangeEmail',arguments: {'type':2}).then((_){
        setState(() {});
      });
    }else if(type == 2){
      if(validateEmail(account!) == false){
        showToast(email_input_error.tr);
        return;
      }
      Navigator.of(context).pushNamed('MinSecurityEmailCode',arguments: {''
          'mail':account}).then((_){
        setState(() {});
      });
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: defaultBlackBgColor,
      appBar: myAppBar(context, 'Email'.tr),
      body: GestureDetector(
        onTap: (){
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 40.w),
          child: Column(
            children: [
              SizedBox(height: 40.w,),
              Container(
                alignment: Alignment.centerLeft,
                child: Text(type == 1?'Email account has been bound'.tr:'Enter a new email account'.tr,style: TextStyle(
                  color: Colors.white,
                  fontSize: 32.sp,
                  fontWeight: FontWeight.w600
                ),),
              ),
              SizedBox(height: 32.w,),
              Container(
                width: 670.w,
                height: 108.w,
                padding: EdgeInsets.symmetric(horizontal: 30.w),
                decoration: BoxDecoration(
                    border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 1.w),
                    borderRadius: BorderRadius.circular(20.w)
                ),
                child:  Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(child: TextField(
                      //控制器
                      textInputAction: TextInputAction.done,
                      controller: accountController,
                      maxLength: 20,
                      maxLines: 1,
                      //是否自动更正
                      autocorrect: true,
                      enabled: type != 1,
                      //是否自动对焦
                      autofocus: false,
                      style: inputStyle,
                      inputFormatters: [

                      ],
                      decoration: InputDecoration(
                        contentPadding: const EdgeInsets.symmetric(vertical: 0,horizontal: 0),
                        hintText: 'Email address'.tr,
                        hintStyle: inputHitStyle,
                        counterText: "",
                        border: OutlineInputBorder(
                            borderSide: BorderSide.none),
                      ),
                      onChanged: (val){
                        setState(() {
                          account = val.trim();
                        });
                      },
                    )),
                    SizedBox(width: 20.w,),
                    Visibility(visible: account!=null&&account!.isNotEmpty && type == 2,
                      child: GestureDetector(
                        onTap: (){
                          setState(() {
                            accountController.text = '';
                            account = null;
                          });
                        },
                        child: Container(
                          child: inputImg,
                        ),
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(height: 48.w,),
              GestureDetector(
                onTap: (){
                  FocusScope.of(context).requestFocus(FocusNode());
                  _register();
                },
                child: Container(
                  child: Text(type == 1?'Change Email'.tr:'Get Verification Code'.tr,style: TextStyle(
                      color: Colors.white,
                      fontSize: 28.sp
                  ),),
                  decoration: BoxDecoration(
                      color: account != null && account!.isNotEmpty ? themeColor : themeBlueDisableColor,
                      borderRadius: BorderRadius.circular(8.w)
                  ),
                  height: 108.w,
                  alignment: Alignment.center,
                ),
              ),

            ],
          ),
        ),
      ),
    );
  }

}
